import {ValidationProvider,setInteractionMode,configure} from 'vee-validate';
import 'tippy.js/dist/tippy.css';
import 'tippy.js/animations/scale.css';
import tippy from 'tippy.js';
import Vue from 'vue';
import TipContent from './TipContent';

const render=ValidationProvider.options.render;
//设置自定义校验时机
setInteractionMode('custom',(context) => {
	return {
		on:['input','blur','on-blur','on-change']
	};
});
configure({
	bails:false,
	useConstraintAttrs:false,
});
/**
 * @author 唐国雄
 * 表单校验
 * 在vee-validate的ValidationProvider组件基础上增加了错误提示UI
 * :append-to		提示元素绑定在哪里,默认document.body
 */
export default {
	name:'ValidationProvider',
	extends:ValidationProvider,
	props:{
		//提示元素绑定在哪里,默认document.body
		appendTo:null,
	},
	computed:{
		tippyOptions(){
			return {
				theme:'error-tip',
				animation:'scale',
				interactive:true,
				hideOnClick:false,
				content:this.tipContent.$el,
				appendTo:this.appendTo??document.body,
			};
		},
	},
	watch:{
		errors(errors){
			if(errors.length>0){
				Object.assign(this.tipContent,{
					errors
				});
				this.tipInstance.enable();
				if(this.hover){
					this.tipInstance.show();
				}
			}else{
				this.tipInstance.disable();
			}
		}
	},
	mounted(){
		this.$nextTick(function(){
			this.tipContent=new Vue(TipContent).$mount();
			this.tipInstance=tippy(this.$el,this.tippyOptions);
			this.tipInstance.disable();
			this.$watch('tippyOptions',function(val){
				this.tipInstance.setProps(val);
			});
		});
	},
	beforeDestroy(){
		this.$nextTick(function(){
			this.tipContent.$destroy();
			this.tipInstance.destroy();
		});
	},
	render(h){
		const vnode=render.call(this,h);
		vnode.data={
			staticClass:'lexmis-ValidationProvider',
			on:{
				mouseenter:() => {
					this.hover=true;
				},
				mouseleave:() => {
					this.hover=false;
				}
			}
		};
		return vnode;
	}
};
